#include "component/component.h"
#include "motovis.h"

namespace motovis
{

using namespace std::chrono_literals;

Component::Component(const std::string& component_name)
    : name_(component_name)
    , period_(1000ms)
    , affinity_(-1)
    , priority_(-1)
{
    node_ = createNode(name_);
}

Component::~Component()
{
    task_->join();
}

void Component::StartMainTask(const std::chrono::milliseconds& mil_secs, const int priority, const int affinity)
{
    task_ = std::make_shared<std::thread>(std::bind(&Component::Exec, this));
    period_ = mil_secs;
    priority_ = priority;
    affinity_ = affinity;
}

void Component::Exec()
{
    // update thread attributes
    // if (affinity_ != -1) {
    //     cpu_set_t cpuset;
    //     CPU_ZERO(&cpuset);
    //     CPU_SET(affinity_, &cpuset);
    //     auto ret = pthread_setaffinity_np(task_->native_handle(), sizeof(cpu_set_t), &cpuset);
    //     if (ret != 0) {
    //         std::cerr << "Error calling pthread_setaffinity_np" << std::endl;
    //     }
    // }

    // if (priority_ != -1) {
    //     struct sched_param sch_params;
    //     sch_params.sched_priority = priority_;
    //     auto ret = pthread_setschedparam(task_->native_handle(), SCHED_RR, &sch_params);
    //     std::cout << "pthread_setschedparam: " << ret << std::endl;
    // }

    for (;;)
    {
        Proc();
        std::this_thread::sleep_for(period_);
    }
}

} // namespace motovis
